package com.briup.corejava.day19;

import com.briup.corejava.day11.pojo.Student;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 使用对象流和文件流
 * 将一个Student类型的集合保存到本地文件里
 */
public class Test1_ow {
    public static void main(String[] args) {
        ObjectOutputStream oos = null;
        FileOutputStream fos = null;

        File file = new File("src/com/briup/corejava/day19/file/a.txt");

        try {
            fos = new FileOutputStream(file);
            oos = new ObjectOutputStream(fos);
            // 准备对象
            List<Student> list = new ArrayList<>();
            list.add(new Student("张三",20));
            list.add(new Student("李四",19));
            list.add(new Student("王武",21));

            // 写出对象
            oos.writeObject(list);
            oos.flush();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if(fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if(oos != null) {
                try {
                    oos.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
